package com.monkeyboy.demo.base.producer;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;

import java.util.concurrent.TimeUnit;

/**发送异步消息
 * @Author Gavin
 * @date 2020.08.18 12:30
 */
public class AsyncProducer {
    public static void main(String[] args) throws Exception{
        //        1.创建消费者Consumer，制定消费者组名,唯一
        DefaultMQProducer producer = new DefaultMQProducer("group1");
//        2.指定Nameserver地址
        producer.setNamesrvAddr("192.168.1.140:9876;192.168.1.141:9876");
//        3.启动producer
        producer.start();
        for (int i = 10; i <20 ; i++) {
            //4.创建消息对象，指定主题Topic,Tag和消息体
            /**
             * 参数一：消息主题Topic(相当于就是消息的类别);
             * 参数二：消息Tag(小类别)
             * 参数三：消息内容
             */
            Message msg=new Message("base","Tag2",i+"",("Hello World"+i).getBytes());
            //发送异步消息
            producer.send(msg, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                System.out.println("异步发送结果："+sendResult);
                }
                @Override
                public void onException(Throwable throwable) {
                    System.out.println("发送异常");
                }
            });
            TimeUnit.SECONDS.sleep(1);
        }
        //关闭生产者producer
        producer.shutdown();
    }
}
